import React from 'react';
import { Link, history } from 'umi';
import styles from './topNav.less';

class TopNav extends React.Component {
  state = {
    list: [
      { name: '推荐', path: '/discover' },
      { name: '排行榜', path: '/discover/toplist' },
      { name: '歌单', path: '/discover/playlist' },
    ],
    active: 0,
  };
  // 解决刷新active不正确的问题
  componentDidMount() {
    let { list } = this.state;
    list.forEach((v, index) => {
      if (v.path === history.location.pathname) {
        this.setState({ active: index });
      }
    });
  }
  // 切换路径
  changePath = (index) => {
    this.setState({ active: index });
  };

  render() {
    let { active } = this.state;
    let navList = this.state.list.map((item, index) => {
      let backgroundColor = active === index ? '#9b0909' : '';
      return (
        <Link
          style={{ color: 'white', backgroundColor }}
          className={styles['nav-item']}
          key={index}
          to={item.path}
          onClick={() => this.changePath(index)}
        >
          {item.name}
        </Link>
      );
    });

    return (
      <div className={styles['top-bar']}>
        <div className={styles['content'] + ' content-box'}>{navList}</div>
      </div>
    );
  }
}

export default TopNav;
